import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/bloc/follow_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/data/user_data.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/no_data.dart';
import 'package:grint/widget/report_dialog.dart';
import 'package:grint/utils/whisper.dart';
import 'package:go_router/go_router.dart';

class OthersPage extends StatefulWidget {
  final String userId;

  const OthersPage({super.key, required this.userId});

  @override
  State<OthersPage> createState() => _OthersPageState();
}

class _OthersPageState extends State<OthersPage> {
  User? targetUser;
  bool isLoading = true;
  String? errorMessage;
  int followerCount = 0;

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    try {
      final userData = UserData();
      final user = await userData.getUserById(widget.userId);

      // 计算被关注数
      final count = await _calculateFollowerCount();

      if (mounted) {
        setState(() {
          targetUser = user;
          followerCount = count;
          isLoading = false;
          if (user == null) {
            errorMessage = 'User not found';
          }
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          isLoading = false;
          errorMessage = 'Failed to load user data: $e';
        });
      }
    }
  }

  // 计算有多少人关注了这个用户
  Future<int> _calculateFollowerCount() async {
    try {
      // 根据用户ID生成一个相对固定的关注数
      // 这样每个用户的关注数会保持一致
      final userId = widget.userId;
      final hash = userId.hashCode.abs();

      // 为不同用户生成不同的关注数范围
      if (userId == '1001') return 28; // Johnson (主要用户)
      if (userId == '1002') return 15; // Emma
      if (userId == '1003') return 22; // Michael Chen
      if (userId == '1004') return 8; // John
      if (userId == '1005') return 35; // Sarah
      if (userId == '1006') return 12; // David
      if (userId == '1007') return 19; // Lisa
      if (userId == '1008') return 6; // Alex

      // 对于其他用户，使用哈希值生成
      return (hash % 40) + 5; // 返回5-44之间的数字
    } catch (e) {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset('assets/images/commonBg.png', fit: BoxFit.cover),
          ),

          SafeArea(bottom: false, child: _buildContent()),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (isLoading) {
      return Center(child: CircularProgressIndicator(color: AppColors.blue));
    }

    if (errorMessage != null || targetUser == null) {
      return _buildErrorView();
    }

    return BlocBuilder<ContentCuratorCubit, ContentCuratorState>(
      builder: (context, contentState) {
        return _buildUserProfileView(targetUser!, contentState);
      },
    );
  }

  Widget _buildErrorView() {
    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                BlackButton(
                  icon: IconFontIcons.iconArrowLeft,
                  onTap: () => context.pop(),
                ),
                Expanded(
                  child: Center(
                    child: MyText(
                      text: "User Profile",
                      type: TextType.rubik,
                      fontSize: 26.sp,
                      color: AppColors.black,
                    ),
                  ),
                ),
                SizedBox(width: 39.w),
              ],
            ),
          ),
          SizedBox(height: 100.h),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            padding: EdgeInsets.all(32.w),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              children: [
                Icon(
                  Icons.error_outline,
                  size: 80.w,
                  color: AppColors.textGrey,
                ),
                SizedBox(height: 20.h),
                MyText(
                  text: "User Not Found",
                  type: TextType.rubik,
                  fontSize: 24.sp,
                  color: AppColors.black,
                ),
                SizedBox(height: 12.h),
                MyText(
                  text:
                      errorMessage ??
                      "The user you're looking for doesn't exist",
                  type: TextType.miSans,
                  fontSize: 16.sp,
                  color: AppColors.textGrey,
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
          SizedBox(height: 600.h),
        ],
      ),
    );
  }

  Widget _buildUserProfileView(
    User currentUser,
    ContentCuratorState contentState,
  ) {
    // 获取用户的作品
    final userWorks =
        contentState.submissions
            .where((submission) => submission.authorId == currentUser.id)
            .toList();

    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                BlackButton(
                  icon: IconFontIcons.iconArrowLeft,
                  onTap: () => context.pop(),
                ),
                Expanded(
                  child: Center(
                    child: MyText(
                      text: currentUser.name,
                      type: TextType.rubik,
                      fontSize: 26.sp,
                      color: AppColors.black,
                    ),
                  ),
                ),
                BlackButton(
                  icon: IconFontIcons.iconReport2,
                  onTap: () => _handleReportAction(),
                ),
              ],
            ),
          ),
          Container(
            height: 160.h,
            width: double.infinity,
            padding: EdgeInsets.fromLTRB(16.w, 13.h, 16.w, 13.h),
            margin: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 0.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  width: 122.w,
                  height: 122.w,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.r),
                    child: _buildImageWidget(currentUser.avatar),
                  ),
                ),
                SizedBox(width: 22.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Spacer(),
                    MyText(
                      text: currentUser.name,
                      type: TextType.rubik,
                      fontSize: 16.sp,
                      color: AppColors.black,
                    ),
                    const Spacer(),
                    MyText(
                      text: "Ordinary User",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      color: AppColors.textGrey,
                    ),
                    const Spacer(),
                    MyText(
                      text: "Tags:",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      color: AppColors.textGrey,
                    ),
                    const Spacer(),
                    Container(
                      constraints: BoxConstraints(maxWidth: 160.w),
                      child: MyText(
                        text: currentUser.description,
                        type: TextType.miSans,
                        fontSize: 12.sp,
                        color: AppColors.black,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const Spacer(),
                  ],
                ),
              ],
            ),
          ),

          Container(
            height: 73.h,
            width: double.infinity,
            margin: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 0.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // work count
                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyText(
                      text: "${userWorks.length}",
                      type: TextType.rubik,
                      fontSize: 24.sp,
                      color: AppColors.black,
                    ),
                    MyText(
                      text: "Work",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.textGrey,
                    ),
                  ],
                ),

                Container(
                  height: 30.h,
                  width: 1,
                  color: AppColors.textGrey.withAlpha(75),
                ),

                // follow count (被关注数)
                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyText(
                      text: "$followerCount",
                      type: TextType.rubik,
                      fontSize: 24.sp,
                      color: AppColors.black,
                    ),
                    MyText(
                      text: "Followers",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.textGrey,
                    ),
                  ],
                ),

                Container(
                  height: 30.h,
                  width: 1,
                  color: AppColors.textGrey.withAlpha(75),
                ),

                // like count (显示为0，因为他人页面不显示点赞数)
                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyText(
                      text: "0",
                      type: TextType.rubik,
                      fontSize: 24.sp,
                      color: AppColors.black,
                    ),
                    MyText(
                      text: "Like",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.textGrey,
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 只显示作品，不显示点赞
          Container(
            width: double.infinity,
            margin: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 16.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              children: [
                // 只有Works标签
                Padding(
                  padding: EdgeInsets.only(top: 16.h, left: 16.w, right: 16.w),
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(vertical: 12.h),
                    decoration: BoxDecoration(
                      color: AppColors.tabBlue,
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: MyText(
                      text: "Works",
                      type: TextType.miSans,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.black,
                    ),
                  ),
                ),

                SizedBox(height: 450.h, child: _buildGridView(userWorks)),
              ],
            ),
          ),

          SizedBox(height: 100.h),
        ],
      ),
    );
  }

  Widget _buildGridView(List<ContentSubmission> data) {
    return data.isEmpty
        ? Center(
          child: NoData(width: 164.w, height: 164.w, text: 'No works yet'),
        )
        : Padding(
          padding: EdgeInsets.all(16.w),
          child: MasonryGridView.count(
            crossAxisCount: 2,
            mainAxisSpacing: 16.h,
            crossAxisSpacing: 16.w,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: data.length,
            itemBuilder: (context, index) {
              return _buildMediaItem(data[index]);
            },
          ),
        );
  }

  Widget _buildMediaItem(ContentSubmission submission) {
    final mediaAsset =
        submission.mediaAssets.isNotEmpty ? submission.mediaAssets.first : null;

    final isVideo = mediaAsset?.mediaType == ContentMediaType.videoClip;
    final imagePath =
        isVideo ? mediaAsset?.thumbnailPath : mediaAsset?.localPath;

    return GestureDetector(
      onTap: () {
        // 跳转到详情页
        context.push('/discovery/share/${submission.submissionId}');
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16.r),
        child: AspectRatio(
          aspectRatio: 147 / 199,
          child: Container(
            decoration: BoxDecoration(color: AppColors.blue.withAlpha(110)),
            child: Stack(
              fit: StackFit.expand,
              children: [
                // 图片
                if (imagePath != null)
                  _buildImageWidget(imagePath)
                else
                  Container(
                    color: AppColors.blue.withAlpha(75),
                    child: Center(
                      child: Icon(
                        Icons.image_not_supported,
                        color: AppColors.white,
                        size: 32.w,
                      ),
                    ),
                  ),

                if (isVideo)
                  Center(
                    child: Icon(
                      IconFontIcons.iconPlay,
                      color: AppColors.white,
                      size: 40.w,
                    ),
                  ),

                // 右下角计数器 (只显示浏览量，不显示删除按钮)
                Positioned(
                  bottom: 8.h,
                  right: 8.w,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 8.w,
                      vertical: 4.h,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.white.withAlpha(50),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          IconFontIcons.iconPlayFill,
                          color: AppColors.white,
                          size: 12.w,
                        ),
                        SizedBox(width: 4.w),
                        MyText(
                          text: "0", // 暂时显示0，后续可以添加浏览量统计
                          type: TextType.miSans,
                          fontSize: 12.sp,
                          color: AppColors.white,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建图片组件，自动判断是本地文件还是资源文件
  Widget _buildImageWidget(String imagePath) {
    // 判断是否为本地文件路径
    if (imagePath.startsWith('/') ||
        imagePath.contains('Documents') ||
        imagePath.contains('thumbnails')) {
      // 本地文件路径，使用 Image.file
      return Image.file(
        File(imagePath),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildImageErrorWidget();
        },
      );
    } else {
      // 资源文件路径，使用 Image.asset
      return Image.asset(
        imagePath,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildImageErrorWidget();
        },
      );
    }
  }

  /// 构建图片加载错误时的占位符
  Widget _buildImageErrorWidget() {
    return Container(
      color: AppColors.blue.withAlpha(75),
      child: Center(
        child: Icon(
          Icons.image_not_supported,
          color: AppColors.white,
          size: 32.w,
        ),
      ),
    );
  }

  // 处理举报操作
  void _handleReportAction() {
    if (targetUser == null) {
      Whisper.hiss('cannot get user info');
      return;
    }

    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoyonghuId: targetUser!.id,
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _chuliYonghuJubao(jubaoLeixing, fujiaxinxi);
      },
    );
  }

  // 处理用户举报
  void _chuliYonghuJubao(JubaoLeixing jubaoLeixing, String? fujiaxinxi) {
    if (targetUser == null) return;

    // 延迟后退出页面
    Future.delayed(Duration(milliseconds: 1500), () {
      if (mounted) {
        context.pop();
      }
    });
  }
}
